package com.cugmarket.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cugmarket.constant.MessageConstant;
import com.cugmarket.dto.Result;
import com.cugmarket.entity.UserAddress;
import com.cugmarket.mapper.UserAddressMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;

import static com.cugmarket.constant.RedisConstants.LOGIN_USER_KEY;

@RestController
@RequestMapping("/user/address")
@Slf4j
public class UserAddressController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserAddressMapper  userAddressMapper;

    /**
     * 根据用户id查询所有地址
     * @param token
     * @return
     */
    @GetMapping
    public Result addAddress(@RequestHeader("Authorization") String token) {
        // 根据token从redis中查询用户的id信息
        String tokenKey = LOGIN_USER_KEY + token;
        String userId = stringRedisTemplate.opsForValue().get(tokenKey);
        // 根据id查询所有地址信息
        // 构建查询条件
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getUserId, userId);
        List<UserAddress> userAddressList = userAddressMapper.selectList(queryWrapper);
        return Result.success(userAddressList);
    }

    /**
     * 新增用户地址
     * @param token
     * @param userAddress
     * @return
     */
    @PostMapping
    public Result createAddress(@RequestHeader("Authorization") String token,
                                @RequestBody UserAddress userAddress) {
        // 根据token从redis中查询用户的id信息
        String tokenKey = LOGIN_USER_KEY + token;
        String userId = stringRedisTemplate.opsForValue().get(tokenKey);
        // 设置userId到userAddress对象中
        userAddress.setUserId(userId);
        // 调用mapper插入数据
        int rows = userAddressMapper.insert(userAddress);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.error(MessageConstant.INSERT_ERROR);
        }
    }

    /**
     * 修改用户地址
     * @param userAddress
     * @return
     */
    @PutMapping
    public Result updateAddress(@RequestBody UserAddress userAddress) {
        if( userAddress.getId() == null) {
            return Result.error(MessageConstant.SEARCH_ERROR);
        }

        // 确保传入的地址是存在的
        UserAddress existingAddress = userAddressMapper.selectById(userAddress.getId());
        if (existingAddress == null ) {
            return Result.error(MessageConstant.IS_EMPTY);
        }
        BeanUtils.copyProperties(userAddress,existingAddress);
        // 执行更新操作
        int rows = userAddressMapper.updateById(existingAddress);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.error(MessageConstant.UPDATE_ERROR);
        }
    }
    /**
     * 删除用户地址
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result deleteAddress(@PathVariable("id") String id) {
        // 根据id删除地址
        int rows = userAddressMapper.deleteById(id);
        if (rows > 0) {
            return Result.success();
        } else
            return Result.error(MessageConstant.DELETE_ERROR);
    }

    /**
     *  根据id查询地址
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result getAddressApi(@PathVariable("id") String id){
        // 根据id查询地址
        UserAddress existingAddress = userAddressMapper.selectById(id);
        if (existingAddress == null) {
            return Result.error(MessageConstant.IS_EMPTY);
        }
        return Result.success(existingAddress);
    }

}
